package com.dc.sr.util;

import com.google.common.base.Charsets;
import com.google.common.hash.BloomFilter;
import com.google.common.hash.Funnels;
import lombok.Data;
import org.redisson.Redisson;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;

/**
 * 布隆过滤器工具类
 *
 * @author duchao
 */
@Data
@Configuration
@ConfigurationProperties(prefix = "spring.redis")
public class BloomFilterUtil {

    private String host;

    private String port;

    private String username;

    private String password;

    private RedissonClient redissonClient;

    @PostConstruct
    public void init() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://".concat(host).concat(":").concat(port));
        redissonClient = Redisson.create(config);
    }

    /**
     * BloomFilter(redis开源客户端Redisson实现)
     *
     * @param bf                 过滤器名称
     * @param expectedInsertions 数量
     * @param falseProbability   错误率
     * @return
     */
    public RBloomFilter<String> createBloomFilter(String bf, long expectedInsertions, double falseProbability) {
        RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter(bf);
        bloomFilter.tryInit(expectedInsertions, falseProbability);
        return bloomFilter;
    }

    /**
     * BloomFilter(谷歌guava工具类库实现)
     *
     * @param expectedInsertions 数量
     * @param falseProbability   错误率
     * @return
     */
    public BloomFilter<String> createBloomFilter(long expectedInsertions, double falseProbability) {
        BloomFilter<String> bloomFilter = BloomFilter.create(Funnels.stringFunnel(Charsets.UTF_8), expectedInsertions, falseProbability);
        return bloomFilter;
    }
}
